<?php
namespace app\frontend\forms;

use app\models\User;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Password;
use Phalcon\Validation\Validator\Callback;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Confirmation;

class RegisterForm extends FormBase
{
    public function initialize()
    {
        $email = new Text("email");
        $email->addValidators([
            new PresenceOf(['message'=>'邮箱不能为空','cancelOnFail'=>true]),
            new Email(['message' => '清输入正确的邮箱']),
        ]);
        $this->setElement($email,'邮箱',['placeholder'=>'请输入邮箱', 'class'=>'form-control']);

        $username = new Text("username");
        $username->addValidators([
            new PresenceOf(['message'=>'用户名不能为空','cancelOnFail'=>true]),
        ]);
        $this->setElement($username,'用户名',['placeholder'=>'请输入用户名', 'class'=>'form-control']);

        $password = new Password("password");
        $password->addValidators([
            new PresenceOf(['message'=>'密码不能为空','cancelOnFail'=>true]),
            new Confirmation([
                'with'=>[
                    'password'=>'repassword',
                ],
                'message'=>'两次密码输入不一致',
            ]),
            new Callback([
                'callback'=>function($data){
                    $currentModel = User::findFirst([
                        'username = :username:',
                        'bind'=>['username'=>$data['username']]
                    ]);
                    return $currentModel?false:true;
                },
                'message'=>'用户名已存在',
            ])
        ]);
        $this->setElement($password,'密码',['placeholder'=>'请输入密码', 'class'=>'form-control']);

        $repassword = new Text("repassword");
        $repassword->addValidators([
            new PresenceOf(['message'=>'重复密码不能为空','cancelOnFail'=>true]),
        ]);
        $this->setElement($repassword,'重复密码',['placeholder'=>'请输入密码', 'class'=>'form-control']);
    }

}
